package com.gdou.crrp.controller;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.gdou.crrp.entity.Doctor;
import com.gdou.crrp.entity.Evaluate;
import com.gdou.crrp.entity.Hospital;
import com.gdou.crrp.entity.Reservation;
import com.gdou.crrp.service.EvaluateService;
import com.gdou.crrp.service.ReservationService;
import com.sun.org.apache.xpath.internal.operations.Mod;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;

import org.springframework.http.HttpEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;


import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.xml.crypto.Data;

import java.text.DecimalFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;


@Controller
@RequestMapping("/evaluate")
public class EvaluateController {

    @Autowired
    private EvaluateService evaluateService;

    @Autowired
    private ReservationService reservationService;


    private final int pageSize = 3;



    //从toMyEvaluate利用js带个参数过去
//    @RequestMapping("/toEvaluate/{id}")
    @RequestMapping("/toEvaluate")
    public String toEvaluate(Model model, Integer id){
        Reservation re = reservationService.findReservationById(id);
        model.addAttribute("res",re);
        return "evaluate/eval";
    }

    //将数据返回到myEvaluate.html页面上a
    //弹窗事件处理，处理最近的发生的预约事件
    @RequestMapping("/goToEvaluate")
    public String toEvaluate(Model model, HttpSession session){
//        session.setAttribute("uid",1);//该行等用户管理模块完成后需删除
        int uid = (int)session.getAttribute("id");
        String name =evaluateService.findMyName(uid);
        Reservation reservation = evaluateService.findMaxIdIsEval(name);
        if (reservation==null){
            model.addAttribute("theFirstOne",0);
        }else {
            model.addAttribute("theFirstOne",reservation);
        }
        return "evaluate/goToEvaluate";
    }

    //保存用户id为1的评论，设置评论不为空，
    @RequestMapping("/saveEvaluate")
    public String saveEvaluate(Evaluate evaluate,HttpSession session,Integer id) throws ParseException {
//        session.setAttribute("uid",1);//该行等用户管理模块完成后需删除
        int uid = (int)session.getAttribute("id");
        evaluate.setUid(uid);
        /***
         * 插入保存好评率
         */
        List<Integer> goods = evaluateService.findDoctorGood(evaluate.getDoctorName());
        Doctor doctor = evaluateService.findDoctorByName(evaluate.getDoctorName());
        //遍历list里面的内容并全部加起来,获取比例并存进医生中
        String rates = evaluateService.countRate(goods,evaluate.getLevel());
        doctor.setGoodRate(rates);
        evaluateService.saveDoctorRate(doctor);//顺带保存医生的好评率
        evaluateService.saveEvaluate(evaluate,id);
        String url = "redirect:/evaluate/toMyEvaluate?id="+uid;
        return url;
    }



    @RequestMapping("/toMyEvaluate")
    public String toMyEvaluate( Integer id, Map<String,Object> map, Integer pn,HttpSession session){
        if (pn == null){
        pn = 0;
    }
        if (id==null){
          id= (int)session.getAttribute("id");
        }
        System.out.println("id:"+id);
    Pageable pageable = PageRequest.of(pn,5, Sort.Direction.DESC,"evaluateTime");
    Page<Evaluate>  eval= evaluateService.showMyEvalIsEval(id , pageable);
        map.put("pageInfo", eval);
        map.put("uid",id);
        return "evaluate/myEvaluate";
}

    @RequestMapping(value="/findNoEval")
    public HttpEntity<JSONArray> find(@RequestParam(name = "pageNum")int pageNum, HttpSession session) {

//        session.setAttribute("uid",1);//该行等用户管理模块完成后需删除
        int uid = (int)session.getAttribute("id");
        String name = evaluateService.findMyName(uid);
        JSONObject json=new JSONObject();
        JSONArray jsonArray=new JSONArray();
        System.out.println(pageNum);
        int page = pageNum -1;
// 定义的总记录数
        int dataCount = 0;
// 定义当前页
//  pageNum = 1;
// 定义总页数
        int pageCount = 0;
// 定义每页显示条数

// 开始索引
        int startIndex = 0;
        dataCount=evaluateService.countId(name,0);
        if(dataCount%pageSize == 0){
            pageCount = dataCount/pageSize;
        }else {
            pageCount = dataCount/pageSize + 1;
        }
        if(pageNum!=0){
            startIndex = (pageNum-1)*pageSize;
        }
        List<Reservation> res=evaluateService.showMyEvalNoEval(name,0,page,pageSize);
        System.out.println("我我我："+res);
        json.put("dataCount", dataCount);
        json.put("pageNum", pageNum);
        json.put("pageCount", pageCount);
        jsonArray.add(res);
        jsonArray.add(json);
        HttpEntity<JSONArray> httpEntity=new HttpEntity<>(jsonArray);
        return httpEntity;
    }

    @ResponseBody
    @PostMapping("/saveSecondEvaluate")
    public Evaluate saveAddContent(@RequestParam(name="cid")int cid,@RequestParam(name="content") String content){

        //找到当前评论
        //添加内容
        //返回数据
        return  evaluateService.saveSecondEval(cid,content);
    }
//删除的处理

    /**
     *
     * @param nowPage:当前删除项所在的页数
     * @param totalpage：所有的页数
     * @param itemNum:所有项目的名字
     * @param iId：删除项的id
     * @return
     */
    @ResponseBody
    @PostMapping("/deleteEvaluate")
    public String deleteEval(@RequestParam(name="np") int nowPage,@RequestParam(name="tp") int totalpage,@RequestParam(name = "in") int itemNum,@RequestParam(name = "itemId") int iId,@RequestParam(name = "uid") int uid){
//执行删除操作
        evaluateService.deleteEval(iId);
        int thePage = 0;
        if (totalpage==1){
            thePage = 0;//页数为1页
        }
        else if ((itemNum%pageSize)>1){
            thePage = nowPage-1;//页数为多页
        }
        else {
            thePage = nowPage-2;//页数为多页，但另一页只有一项
        }
        String url = "/evaluate/toMyEvaluate?pn="+thePage+"&id="+uid;
        return url;
    }


//test
    @RequestMapping("/toFindEval")
    public String test(Model model ){
        List<Hospital> allHospital = evaluateService.findAllHospital();
        model.addAttribute("allHospital", allHospital);
        return "evaluate/findEvaluate";
    }

    @ResponseBody
    @PostMapping("/findAllDoctor")
    public List<String> findAllDoctor(Model model){
        List<String> doctors = evaluateService.findAllDoctor();
        return doctors;
    }

//三级栏，按医院与科室进行查找
    @ResponseBody
    @PostMapping("/findByHospitalName")
    public List<Doctor> findByHospitalName(@RequestParam(name = "hospitalName") String hname, @RequestParam(name = "departmentName") String dname, @RequestParam(name = "doctorName") String rname){
    String a = rname;
    String b="请选择";
    System.out.println(a);
        if (a.equals(b)){
            List<Doctor>  doctors1 = evaluateService.findByDepartmentId(hname,dname);
            return doctors1;
        }
       else{
            Doctor doctor =evaluateService.findByHospitalName(hname,dname,rname);//找到该医生
            List<Doctor>   doctors2= new ArrayList<>();
            doctors2.add(doctor);
            return doctors2;
       }
    }
    //直接按姓名进行查找
    @ResponseBody
    @PostMapping("/findByDoctorName")
    public List<Doctor> findByDoctorName(@RequestParam(name = "doctorName") String doctorName){
        List<Doctor>  doctor =evaluateService.findByDoctorName(doctorName);//找到该医生
            return doctor;
    }
    /***
     * 查找该医生所有评价的方法
     * 返回的数据包括：评价人，评价时间，评价内容，评价星级，追评内容
     * @return
     */
@RequestMapping ("/findEvalAboutDoctor")
public String  findEvalAboutDoctor(String doctorName ,Model model){
   //按医生姓名查找评论
        List<Object> eval = evaluateService.listAllEval(doctorName);
        System.out.println("eval"+eval.size());
        int fiveStarNum = evaluateService.countStars(doctorName,5);
        int twoThreeFourNum = evaluateService.countStars(doctorName,3);
        int oneStarNum = evaluateService.countStars(doctorName,1);
        int hasAddContent = evaluateService.countaddContentNum(doctorName);

   //查找到好评，并统计出所有的评价数
        model.addAttribute("eadList",eval);
        model.addAttribute("evalNum",eval.size());//总评价
        //将医生姓名传入下一个页面
        model.addAttribute("theDoctor",doctorName);
        model.addAttribute("five",fiveStarNum);
        model.addAttribute("twoToFour",twoThreeFourNum);
        model.addAttribute("one",oneStarNum);
        model.addAttribute("hasAdd",hasAddContent);
        return "evaluate/showAllEval";
}

    /***
     *
     * @param name
     * @param num:-1表示全部，3表示2，3，4星，5表示5星,
     * @return
     */
    @ResponseBody
    @PostMapping("/findEvalByStar")
public List<Object> findEvalByStar(@RequestParam(name="doctorName")String name,@RequestParam(name="number")int num){
        List<Object> list = new ArrayList<>();
        System.out.println("num"+num);
        int num1 = num;
              if (num1==-1){
                  list = evaluateService.listAllEval(name);

              }else if(num1==-2){
                list = evaluateService.listAllEvalHasAdd(name);
              }else {
                  list = evaluateService.evalDiffLevel(name,num1);
              }
              System.out.println("list:"+list);
              return list;
}

//进行评价操作
    @RequestMapping("/test")
    public String  test(Model model,HttpSession httpSession){
//        将信息存储进数据库
//        httpSession.setAttribute("uid",1);//该行等用户管理模块完成后需删除
        int uid = (int)httpSession.getAttribute("id");
        String name =evaluateService.findMyName(uid);
        Date date = new Date();
        model.addAttribute("date",date);
        Reservation reservation = evaluateService.findMaxIdIsEval(name);
            model.addAttribute("theFirstOne",reservation);
        return "evaluate/test";
    }
}
